package cn.huiyunche.bms.backend.service;

import cn.huiyunche.bms.backend.bo.AuditBO;
import cn.huiyunche.bms.backend.constant.AutoConfConstant;
import cn.huiyunche.bms.backend.query.BmsReceiptAuditConditions;
import cn.huiyunche.bms.backend.query.ReceiptAduitWithOrderConditions;
import cn.huiyunche.bms.base.mapper.BmsReceiptAuditAttachMapper;
import cn.huiyunche.bms.base.mapper.BmsReceiptAuditMapper;
import cn.huiyunche.bms.base.mapper.SOrderMapper;
import cn.huiyunche.bms.base.model.*;
import cn.huiyunche.commons.constant.QiniuConstant;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private BmsReceiptAuditMapper auditMapper;
    @Autowired
    private BmsReceiptAuditAttachMapper auditAttachMapper;
    @Autowired
    private SOrderMapper orderMapper;
    @Autowired
    private AutoConfConstant autoConfConstant;
    @Autowired
    private AreaService areaService;

    private static final Logger LOGGER = LoggerFactory.getLogger(AuditServiceImpl.class);

    @Override
    public Integer submitData(BmsReceiptAuditConditions conditions) throws Exception {
        LOGGER.info("AuditServiceImpl.submitData params : {}, {}", conditions);
        if (conditions == null){
            LOGGER.error("AuditServiceImpl.submitData param conditions not be null ");
            throw new IllegalArgumentException("提交信息不能为空！");
        }
        BmsReceiptAudit audit = new BmsReceiptAudit();

        BeanUtils.copyProperties(conditions, audit);
        if(audit.getStatus() == null)
            //状态：10：未提交 20：已提交 30：已通过 40：未通过"
            audit.setStatus("20");

        if (conditions.getPicKey() == null){
            LOGGER.error("AuditServiceImpl.submitData param picKey not be null ");
            throw new IllegalArgumentException("附件图片key不能为空！");
        }
        List<String> pickeyList = JSONArray.parseArray(conditions.getPicKey(), String.class);

        if (audit.getSalesOrderCode() == null){
            LOGGER.error("AuditServiceImpl.submitData param salesOrderCode not be null ");
            throw new IllegalArgumentException("销售订单号不能为空！");
        }
        //查询客户订单ID和客户订单号
        SOrderExample orderExample = new SOrderExample();
        orderExample.createCriteria().andOutOrderCodeEqualTo(audit.getSalesOrderCode());
        List<SOrder> orders = orderMapper.selectByExample(orderExample);
        if (orders.size()>0){
            audit.setCustomerOrderId(orders.get(0).getId().intValue());
            audit.setCustomerOrderCode(orders.get(0).getOrderCode());
        }else {
            LOGGER.error("AuditServiceImpl.submitData : order is null");
            throw new IllegalArgumentException("订单信息为空！");
        }

        try {
            BmsReceiptAuditExample example = new BmsReceiptAuditExample();
            example.createCriteria().andSalesOrderCodeEqualTo(conditions.getSalesOrderCode());
            List<BmsReceiptAudit> examples = auditMapper.selectByExample(example);
            if (examples.size()>0){
                //更新收款审核表
                audit.setId(examples.get(0).getId());
                audit.setCreateUser(examples.get(0).getCreateUser());
                audit.setModifiedUser(conditions.getCreateUser());
                audit.setGmtModified(new Date());
                auditMapper.updateByPrimaryKeySelective(audit);
                //更新收款审核附件为已删除状态
                BmsReceiptAuditAttachExample auditAttachExample =  new BmsReceiptAuditAttachExample();
                auditAttachExample.createCriteria().andSalesOrderIdEqualTo(conditions.getSalesOrderId());
                BmsReceiptAuditAttach auditAttach = new BmsReceiptAuditAttach();
                auditAttach.setDeleteMark((byte)0);
                auditAttachMapper.updateByExampleSelective(auditAttach, auditAttachExample);
            }else {
                //插入收款审核表
                auditMapper.insertSelective(audit);
            }
            //插入收款审核附件表
            if (pickeyList.size() > 0) {
                for (String str : pickeyList) {
                    BmsReceiptAuditAttach auditAttach = new BmsReceiptAuditAttach();
                    auditAttach.setCustomerOrderId(audit.getCustomerOrderId());
                    auditAttach.setSalesOrderId(conditions.getSalesOrderId());
                    auditAttach.setPicKey(str);
                    auditAttach.setCreateUser(conditions.getCreateUser());
                    auditAttachMapper.insertSelective(auditAttach);
                }
            }
        } catch (Exception e) {
            LOGGER.error("AuditServiceImpl.submitData param submit not be null ");
            throw new IllegalArgumentException("提交收款审核数据失败！");
        }
        return null;
    }

    @Override
    public Integer callSales(String salesOrderCode, String status) throws Exception {
        String url = autoConfConstant.getSales()+ "/api/order/updateAttachAuditStatus";
        Integer time = autoConfConstant.getSalesTime();
        Map<String, Object> map = new HashMap<>();
        map.put("orderCode", salesOrderCode);
        map.put("attachAuditStatus", status);
        String result = HttpRequestUtil.sendHttpPost(url, map, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
//            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            if (!success) {
                LOGGER.error("AuditServiceImpl callSales result error");
                throw new BusinessException(msgCode, msg);
            }else {
                LOGGER.info("AuditServiceImpl callSales result success");
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> selectReceiptAuditByConditions(PageVo pageVo, ReceiptAduitWithOrderConditions conditions) throws Exception {
        LOGGER.info("AuditServiceImpl.selectReceiptAuditByConditions params : {}, {}", pageVo, conditions);
        Map<String, Object> map = new HashMap<>();
        String orderByClause = null;
        if (null != pageVo) {
            orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " r.id DESC";
        }
        Map<String, Object> conMap = new HashMap<>();
        conMap.put("status", conditions.getStatus());
        conMap.put("auditStatus", conditions.getAuditStatus());
        conMap.put("departProvinceCode", conditions.getDepartProvinceCode());
        conMap.put("departCityCode", conditions.getDepartCityCode());
        conMap.put("departCountyCode", conditions.getDepartCountyCode());
        conMap.put("receiptProvinceCode", conditions.getReceiptProvinceCode());
        conMap.put("receiptCityCode", conditions.getReceiptCityCode());
        conMap.put("receiptCountyCode", conditions.getReceiptCountyCode());
        conMap.put("outOrderCode", conditions.getOutOrderCode());
        conMap.put("createTimeEnd", conditions.getCreateTimeEnd());
        conMap.put("createTimeStart", conditions.getCreateTimeStart());
        if (null != pageVo) {
            pageVo.setTotalRecord(auditMapper.queryListByConditionsCount(conMap));
            conMap.put("limitStart", pageVo.getStartIndex());
            conMap.put("limitEnd", pageVo.getPageSize());
            conMap.put("orderByClause", orderByClause);
        }
        List<ReceiptAuditWithOrder> list = auditMapper.queryListByConditions(conMap);
        map.put("list", list);
        List<BArea> areaList = areaService.queryProvince();
        map.put("areaList", areaList);
        if (null != pageVo) {
            map.put("page", pageVo);
        }
        return map;
    }

    @Override
    public AuditBO detail(AuditBO bo) throws Exception {
        if (Objects.equals(bo.getId(), 0) || Objects.equals(bo.getId(), null)) {
            LOGGER.info("AuditServiceImpl.detail param bo.getId must not be null");
            throw new IllegalArgumentException("查询条件ID不能为空");
        }
        List<String> list = auditAttachMapper.queryPicKeyByAuditId(bo.getId());
        List<String> listUrl = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(item -> {
                listUrl.add(QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, item, "", "", ""));
            });
            bo.setPicList(listUrl);
        }
        return bo;
    }

    @Override
    public Integer updateStatus(ReceiptAduitWithOrderConditions conditions) throws Exception {
        LOGGER.info("AuditServiceImpl.updateStatus params : {}, {}", conditions);
        BmsReceiptAudit audit = new BmsReceiptAudit();
        try {
            audit.setId(conditions.getId());
            audit.setStatus(conditions.getAuditStatus());
            if (conditions.getComment() != null)
                audit.setComment(conditions.getComment());
            audit.setAuditUser(conditions.getAuditUser());
            audit.setGmtAudit(new Date());
            auditMapper.updateByPrimaryKeySelective(audit);
        }catch (Exception e){
            LOGGER.error("AuditServiceImpl updateStatus result error");
            throw new IllegalArgumentException("审核失败！");
        }
        try {
            if ("30".equals(conditions.getAuditStatus())){
                SOrder order = new SOrder();
                audit = auditMapper.selectByPrimaryKey(conditions.getId());
                order.setPayStatus(30);
                order.setId(audit.getCustomerOrderId().longValue());
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }catch (Exception e){
            LOGGER.error("AuditServiceImpl updateStatus result error：修改订单支付状态失败");
            throw new IllegalArgumentException("修改订单支付状态失败！");
        }
        try {
            callSales(conditions.getOutOrderCode(), conditions.getAuditStatus());
        }catch (Exception e){
            LOGGER.error("AuditServiceImpl updateStatus result error：修改销售端状态失败");
            throw new IllegalArgumentException("修改销售端状态失败！");
        }
        return null;
    }
}
